<template>
  <div>
    <!-- 搜索栏 -->
    <Row>
      <Card>
        <Form ref="search" :model="searchData" :rules="searchReg" :label-width="80">
          <Row>
            <i-col :xs="24" :md="12" :lg="6">
              <FormItem label="问卷标题" prop="examName">
                <Input
                  v-model="searchData.examName"
                  suffix="ios-search"
                  placeholder="请输入问卷标题"
                  style="width: auto"
                >
                  <Icon type="ios-search" slot="suffix" />
                </Input>
              </FormItem>
            </i-col>
          </Row>
          <FormItem>
            <Button
              v-if="btnAccess.query"
              type="primary"
              style="marigin:0 20px"
              :loading="searchLoading"
              @click="searchSubmit(10,1)"
            >提交搜索</Button>
            <Button @click="submitReset">重置搜索</Button>
          </FormItem>
        </Form>
      </Card>
    </Row>
    <!-- 表格栏 -->
    <Row style="margin-top:20px">
      <Card>
        <div class="btn-arrs">
          <Button v-if="btnAccess.add" type="info" @click="insertMeasurement">添加测评</Button>
        </div>
        <Table
          border
          tooltip
          highlight-row
          :loading="tabelLoading"
          ref="currentRowTable"
          :columns="tabelTitle"
          :data="tabelContent"
          height="500"
        ></Table>
        <div style="margin-top:20px;margin-left:35%">
          <Page
            @on-change="pageNumberChange"
            :page-size="pageSize"
            :total="pageTotal"
            @on-page-size-change="pageSizeChange"
            show-elevator
            show-sizer
          />
        </div>
        <!-- <Upload
          :on-success="handleSuccess"
          :format="['xls','xlsx']"
          :on-format-error="handleFormatError"
          action="api/assessmentTest/importMeasurement"
        >
          <Button icon="ios-cloud-upload-outline">上传测评</Button>
        </Upload>-->
      </Card>
    </Row>
    <!-- 添加/修改测评模态框 -->
    <Modal v-model="isShowModal" :title="modalTitle" @on-cancel="cancelModal" width="700px">
      <Form ref="formsData" :model="formsData" :rules="formReg" :label-width="80">
        <Row>
          <Col span="24">
            <FormItem label="问卷标题" prop="examName">
              <Input v-model="formsData.examName" placeholder="请输入问卷标题"></Input>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="12">
            <FormItem label="问卷类别" prop="examType">
              <Select v-model="formsData.examType" placeholder="请选择问卷类别" style="width:190px;">
                <Option value="1">问卷类别一</Option>
                <Option value="2">问卷类别二</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="测评年份" prop="datetime">
              <DatePicker
                type="year"
                format="yyyy"
                @on-change="modalDatetimeFunc"
                :value="formsData.datetime"
                placeholder="请输入测评年份"
              ></DatePicker>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button
          v-if="btnAccess.upd"
          type="primary"
          size="large"
          :loading="modalLoading"
          @click="submitModal"
        >提交</Button>
        <Button size="large" @click="cancelModal">取消</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import { measurementAjax, measurementDataAjax } from "@/api/measurement";
// 查询
const QUERY_URL = "/examIndex/query";
// 添加URL
const INSERT_URL = "/examIndex/insert";
// 修改URL
const UPDATE_URL = "/examIndex/update";
// 删除
const DELETE_URL = "/examIndex/delete";
const INSERT_TITLE = "添加测评";
const UPDATE_TITLE = "编辑测评";
export default {
  data() {
    return {
      // 增删改查权限按钮
      btnAccess: {
        add: true,
        add2: "inline-block",
        del: "inline-block",
        upd: true,
        query: true
      },
      tabelLoading: false,
      searchLoading: false,
      searchData: {
        testObj: [],
        examName: "", // 问卷标题
        examType: "", // 问卷类别
        examer: "", // 测评对象
        startDate: "",
        endDate: ""
      },
      tabelTitle: [
        {
          title: "问卷标题",
          key: "examName"
        },
        {
          title: "问卷类别",
          key: "examType",
          render: (h, params) => {
            let text = "";
            if (params.row.examType === "1") {
              text = "类型一";
            } else {
              text = "类型二";
            }
            return h("div", {}, text);
          }
        },
        {
          title: "测评年份",
          key: "datetime"
        },
        {
          title: "操作",
          key: "action",
          width: 220,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.formsData = Object.assign({}, params.row);
                      this.modalTitle = UPDATE_TITLE;
                      this.isShowModal = true;
                    }
                  }
                },
                "编辑"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "success",
                    size: "small"
                  },
                  style: {
                    margin: "0  5px",
                    display: this.btnAccess.add2
                  },
                  on: {
                    click: () => {
                      // 跳转一类问卷或者二类问卷
                      const id = params.row.id; // 赋值id跳转
                      if (params.row.examType === "1") {
                        this.$router.push({
                          name: "measurement_generates",
                          params: {
                            id
                          }
                        });
                      } else if (params.row.examType === "2") {
                        this.$router.push({
                          name: "measurement_generate2s",
                          params: {
                            id
                          }
                        });
                      }
                    }
                  }
                },
                "生成问卷"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  style: {
                    display: this.btnAccess.del
                  },
                  on: {
                    click: () => {
                      this.$Modal.confirm({
                        title: "删除测评",
                        content: "<p>删除后将无法恢复！</p>",
                        loading: true,
                        onOk: () => {
                          var formData = Object.assign(
                            {},
                            {
                              id: params.row.id
                            }
                          );
                          var url = DELETE_URL;
                          var keyOne = "entity";
                          measurementAjax({ formData, url, keyOne })
                            .then(result => {
                              this.$Modal.remove();
                              if (
                                result.data.code === "200" &&
                                result.data !== undefined
                              ) {
                                this.$Message.success("删除成功");
                                this._getMeasurementData(
                                  this.searchData,
                                  this.pageSize,
                                  this.pageNumber
                                );
                              } else {
                                this.$Message.error(result.data.message);
                              }
                            })
                            .catch(err => {
                              console.log(err);
                            });
                        }
                      });
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
      tabelContent: [],
      searchReg: {},
      pageTotal: 10,
      pageNumber: 1,
      pageSize: 10,
      testObj: [],
      // 弹窗form 表单
      formsData: {
        examName: "", // 问卷标题
        examer: "", // 测评对象
        examType: "", // 问卷类别
        startDate: "",
        endDate: "",
        datetime: ""
      },
      modalTitle: "添加",
      isShowModal: false,
      modalLoading: false,
      // 模态框form 表单
      formReg: {
        examName: [
          {
            required: true,
            message: "请输入问卷标题",
            trigger: "blur"
          }
        ],
        examType: [
          {
            required: true,
            message: "请选择问卷类别",
            trigger: "change"
          }
        ],
        datetime: [
          {
            required: true,
            type: "string",
            message: "请选择年份",
            trigger: "change"
          }
        ]
      }
    };
  },
  filters: {
    optionName(value) {
      var subTitle = "";
      switch (value) {
        case 0:
          subTitle = "选项A：";
          break;
        case 1:
          subTitle = "选项B：";
          break;
        case 2:
          subTitle = "选项C：";
          break;
        case 3:
          subTitle = "选项D：";
          break;
        case 4:
          subTitle = "选项E：";
          break;
        default:
          subTitle = "选项F：";
          break;
      }
      return subTitle;
    }
  },
  methods: {
    handleSuccess(res, file) {
      if (res.code === "200") {
        this.$Notice.success({
          title: res.message,
          desc: res.results
        });
      } else {
        this.$Notice.error({
          title: res.message,
          desc: res.results
        });
      }
    },
    // 验证上传格式
    handleFormatError(file) {
      this.$Notice.warning({
        title: "文件格式错误",
        desc: "文件" + file.name + " 格式错误, 请选择xls或者xlsx"
      });
    },
    inserOption(vla) {
      var i = 1;
      this.options.push(i++);
    },
    // 添加测评
    insertMeasurement() {
      this.modalTitle = INSERT_TITLE;
      this.isShowModal = true;
      this.$refs["formsData"].resetFields();
      this.formsData.id = ""; // 清除id
    },
    // 开始日期
    searchSelectStart(date) {
      this.searchData.startDate = date;
    },
    // 截止日期
    searchSelectEnd(date) {
      this.searchData.endDate = date;
    },
    // 页码
    pageNumberChange(pageNumber) {
      this.pageNumber = pageNumber;
      this._getMeasurementData(this.searchData, this.pageSize, this.pageNumber);
    },
    // 页数
    pageSizeChange(pageSize) {
      this.pageSize = pageSize;
      this._getMeasurementData(this.searchData, this.pageSize, this.pageNumber);
    },
    submitReset() {
      this.searchData = {
        testObj: [],
        name: "",
        type: "",
        startDate: "",
        endDate: ""
      };
      this.searchLoading = false;
    },
    // 搜索提交
    searchSubmit(pageSize, pageNumber) {
      this.pageSize = pageSize;
      this.pageNumber = pageNumber;
      this.searchLoading = true;
      this._getMeasurementData(this.searchData, this.pageSize, this.pageNumber);
    },
    // 查询
    _getMeasurementData(searchData, pageSize, pageNumber) {
      this.tabelLoading = true;
      var url = QUERY_URL;
      var keyOne = "filter";
      var keyTwo = "";
      var formData = Object.assign(searchData, {
        pageSize: pageSize,
        pageNumber: pageNumber
      });
      measurementAjax({ formData, url, keyOne, keyTwo })
        .then(result => {
          this.tabelLoading = false;
          this.searchLoading = false;
          if (result.data.code === "200" && result.data !== undefined) {
            this.tabelContent = result.data.results.list;
            this.pageTotal = parseInt(result.data.results.pageTotal);
          } else {
            this.$Message.error(result.data.message);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 模态框事件
    cancelModal() {
      this.isShowModal = false;
      this.modalLoading = false;
    },
    modalDatetimeFunc(date) {
      this.formsData.datetime = date;
    },
    modalStartdateFunc(date) {
      this.formsData.startDate = date;
    },
    modalEnddateFunc(date) {
      this.formsData.endDate = date;
    }, // 添加/修改
    _measurementDataAjax(formData, url) {
      const keyOne = "entity";
      return new Promise((resolve, reject) => {
        measurementDataAjax({ formData, url, keyOne })
          .then(result => {
            if (result.data !== undefined) {
              resolve(result.data);
            } else {
              reject(err);
            }
          })
          .catch(err => {
            console.log(err);
          });
      });
    },
    // 提交模态框
    submitModal() {
      this.$refs["formsData"].validate(valid => {
        if (valid) {
          this.modalLoading = true;
          if (this.modalTitle === INSERT_TITLE) {
            this._measurementDataAjax(this.formsData, INSERT_URL).then(
              result => {
                this.isShowModal = false;
                this.modalLoading = false;
                if (result.code === "200") {
                  this.$Message.success("添加成功！");
                  this._getMeasurementData(
                    this.searchData,
                    this.pageSize,
                    this.pageNumber
                  );
                } else {
                  this.$Message.error(result.message);
                }
              }
            );
          } else if (this.modalTitle === UPDATE_TITLE) {
            this._measurementDataAjax(this.formsData, UPDATE_URL).then(
              result => {
                this.isShowModal = false;
                this.modalLoading = false;
                if (result.code === "200") {
                  this.$Message.success("修改成功！");
                  this._getMeasurementData(
                    this.searchData,
                    this.pageSize,
                    this.pageNumber
                  );
                } else {
                  this.$Message.error("修改失败！");
                }
              }
            );
          }
        } else {
          this.$Message.error("请填写完整！");
        }
      });
    }
  },
  created() {
    this._getMeasurementData(this.searchData, this.pageSize, this.pageNumber);
    this.getDepartmentList.forEach(item => {
      item = Object.assign(
        {},
        {
          value: item,
          label: item
        }
      );
      this.testObj.push(item);
    });
    // 获取按钮权限
    let btnAccess = sessionStorage.getItem("btnaccess");
    this.globalFunction(btnAccess);
  },
  computed: {
    getDepartmentList() {
      return this.$store.state.user.departmentList;
    }
  }
};
</script>
<style>
.demo-drawer-footer {
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background: #fff;
}
</style>
